package com.czk.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 利用stream多线程排序与单线程排序比较
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/26 15:41
 */
public class StreamSort {
    public static void main(String[] args) {
        // 顺序流排序花费耗时：837 ms
        single();
        // 多线程流流排序花费耗时：487 ms
        paralle();
    }

    public static void single() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            // 加入集合
            list.add(UUID.randomUUID().toString());
        }
        long start = System.nanoTime();
        // 排序
        long count = list.stream().count();
        System.out.println(count);
        long end = System.nanoTime();
        long millis = TimeUnit.NANOSECONDS.toMillis(end - start);
        System.out.printf("顺序流排序花费耗时：%d ms%n", millis);
    }

    public static void paralle() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            // 加入集合
            list.add(UUID.randomUUID().toString());
        }
        long start = System.nanoTime();
        // 排序
        long count = list.stream().parallel().count();
        System.out.println(count);
        long end = System.nanoTime();
        long millis = TimeUnit.NANOSECONDS.toMillis(end - start);
        System.out.printf("多线程流流排序花费耗时：%d ms%n", millis);
    }
}
